package com.zhida.jiyangcenter.utils


import android.app.Activity
import chooongg.base.manager.app
import chooongg.base.utils.startActivity
import chooongg.base.utils.toast
import com.alipay.sdk.app.PayTask
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.order.PaySuccessActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/**
 * 封装支付宝支付
 */

class AliPay(val activity: Activity) {
    fun pay(body: String, type: String,PayOrderUuid:String,total_money:Double,PayType:Int) {
        GlobalScope.launch(Dispatchers.IO) {
            val alipay = PayTask(activity)
            val result = alipay.payV2(body, true)
            val resultStatus = result["resultStatus"]
            when (resultStatus) {
                "9000" -> withContext(Dispatchers.Main) {
                    if (type=="0"||type=="4"){
                        SP.PayOrderUuid.put(PayOrderUuid)
                        SP.PayType.put(type)
                        for (i in app.activityStack.size - 1 downTo 0) {
                            if (app.activityStack[i] !is MainActivity) {
                                app.activityStack[i].finish()
                            }
                        }
                        app.activityTop.startActivity<PaySuccessActivity> {
                            putExtra("PayOrderUuid",SP.PayOrderUuid.get())
                            putExtra("PayOrderType",SP.PayType.get())
                            putExtra(
                                "PayMoney", total_money
                            )
                            putExtra("PayType", PayType)
                        }
                    }else {
                        for (i in app.activityStack.size - 1 downTo 0) {
                            if (app.activityStack[i] !is MainActivity) {
                                app.activityStack[i].finish()
                            }
                        }
                    }
                    toast("支付成功")
                }
                "8000", "6004" -> toast("正在处理中")
                "4000", "5000" -> toast("购买失败")
                "6001" -> toast("购买取消")
                "6002" -> toast("网络链接异常")
                else -> toast(result["memo"] ?: "未知异常")
            }
        }
    }
}
